import $ from 'jquery'
import imgConfig from '@/assets/scripts/imgConfig.js'
const units = {	
	getQueryString:function(name) {
	    var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
	    var r = window.location.search.substr(1).match(reg);
	    if (r != null) {
	        return unescape(r[2]);
	    }
	    return null;
	},
	AJAX:{
		baseUrl:tocIM_config.httpReqBaseUrl,
		JsonData:function(_method,_url,_data,_success,_error){
			var _self = this;
			$.ajax({
		        type:_method ||'get',
		        url:_self.baseUrl+_url,
		        dataType:'json',		        
		        data:_data,
		        success:_success,
		        error:_error||function(err){
		        	console.log(err)
		        }
	    	});
		},
		FromData:function(_method,_url,_data,_success,_error){
			var _self = this;
			$.ajax({
		        type:_method ||'get',
		        url:_self.baseUrl+_url,
		        processData: false ,
		        contentType:false,	        
		        data:_data,
		        success:_success,
		        error:_error||function(err){
		        	console.log(err)
		        }
			});
		}
	},
	createGroupAvata:function(memMap){
		var avatarList=[];
		Object.keys(memMap).forEach(item=>{
			avatarList.push(memMap[item].avatar);
		});
		var avatarListLength =avatarList.length;
		var canvasInstance = document.createElement('canvas');
		var ctx = canvasInstance.getContext('2d');
		canvasInstance.width=50;
		canvasInstance.height=50;
		ctx.rect(0,0,canvasInstance.width,canvasInstance.height);
		ctx.fillStyle='#ededed';
		ctx.fill();
		var avatarItemWH=parseInt(50/avatarListLength);
		var result=null;
		avatarList.forEach((item,index) =>{
			var avatarimg = new Image;
			avatarimg.crossOrigin ='anonymous';
			avatarimg.src = item;
			avatarimg.onload=function(){
				if(index<3){
					ctx.drawImage(avatarimg,avatarItemWH*index,avatarItemWH*0,avatarItemWH,avatarItemWH);
				}else if (index>=3 &&index<6){
					ctx.drawImage(avatarimg,avatarItemWH*(index-3),avatarItemWH*1,avatarItemWH,avatarItemWH);
				}else if(index>=6){
					ctx.drawImage(avatarimg,avatarItemWH*(index-6),avatarItemWH*2,avatarItemWH,avatarItemWH);
				};
			};	
		});	
		return function(){
			return canvasInstance.toDataURL("image/jpeg",1);
		};
	},
	Scroll:{
		scrollController:{
			isScroll:true,
			lastValue:null,
			action:null,
			el:null
		},
		watchScroll:function(el,callback){
			var _self = this;
			var getElement =this.scrollController.el==null?"#"+el:"#"+this.scrollController.el;
			$(getElement).scroll(function(){
				var $this =$(this),
				viewH =$(this).height(),
				contentH =$(this).get(0).scrollHeight,
				scrollTop =$(this).scrollTop(); 
				if(_self.lastValue==null){
					_self.lastValue=contentH-scrollTop;
				}else{
					contentH-scrollTop>_self.lastValue?_self.action='top':_self.action='bottom';
					_self.lastValue=contentH-scrollTop;
				};
				if(typeof callback == 'function'){
					callback({
						action:_self.action,
						relativeMargin:_self.action=='top'?scrollTop:(contentH - viewH - scrollTop)
					});
				};
			});
		},
		scrollTo:function(el,params,option){
			var _option={
				speed:option==undefined?0:option.speed
			};
			var getElement = this.scrollController.el==null?"#"+el:"#"+this.scrollController.el;
			var scrollToElement=null;
			var scrollTopValue=null;
			if(typeof params=='string' && params.constructor==String){
				console.log('滚动到首尾')
				scrollTopValue= params=='bottom'? $(getElement)[0].scrollHeight:0
			}else{
				console.log('滚动到指定位置')
				scrollToElement = params;
				scrollTopValue =$(scrollToElement).offset().top - 57;
			};
			$(getElement).animate({
				scrollTop:scrollTopValue
			}, _option.speed); 
		}
	},
	parseChatStringToReadable:function(chatString){
		//过滤器realText to readText
		if(chatString!=undefined && chatString!=null && typeof chatString=='string'){
			var _chatString = chatString;
			var _faceList = imgConfig.faceList;
			var rep = new RegExp(/\bt_ej[[][0-9]*[\]]/,'g');
			var indexRep = new RegExp(/\b\d*\d\b/,'g');
			if(_chatString.match(rep)!=null){
				_chatString.match(rep).forEach(function(item){
					var next_chatString=_chatString.replace(item,"<img class='face_item' name='"+item.match(indexRep) +"' src='"+_faceList[item.match(indexRep)]+"'>");
					_chatString=next_chatString;
				});
			};
			return _chatString;
		}else{
			return chatString;
		};
	},
	parseChatStringToRealText:function(readText){
		//过滤器readText to realText
		var results = null;
		var getChatText = readText;
		var imgRep = new RegExp(/<img.*?src=[\'|\"](.*?)[\'|\"].*?[\/]?>/,'g');
		var nameReg = new RegExp(/\bname=[\'|\"]\d*[\'|\"]/,'g');
		var imgDomList = getChatText.match(imgRep);
		if(imgDomList!=null){
			imgDomList.forEach(function(item){
  				getChatText=getChatText.replace(item,'t_ej['+eval(item.match(nameReg)[0])+']');
  			});
  			results=getChatText;
		}else{
			results=getChatText;
		};
		return results;
	},
	formatTime:function(timestamp){
		var getDateString=function(timestamp){
			var getTime = timestamp==undefined?new Date():new Date(parseInt(timestamp));
			var getyear = getTime.getFullYear();
			var getmonth = getTime.getMonth()+1;
			var getdateval = getTime.getDate();
			return {
				timeString:getyear+'-'+getmonth+'-'+getdateval,
				key:parseInt(getyear)+''+parseInt(getmonth)+''+parseInt(getdateval)
			}
		};
		var getTimeString=function(timestamp){
			var getTime = timestamp==undefined?new Date():new Date(parseInt(timestamp));
			var gethours = getTime.getHours();
			var getmin = getTime.getMinutes();
			var getsec = getTime.getSeconds();	
			return {
				timeString:(gethours>=10?gethours:'0'+gethours)+':'+(getmin>=10?getmin:'0'+getmin),
				key:parseInt(gethours)+''+parseInt(getmin)+''+parseInt(getsec)
			}
		};
		if(getDateString(timestamp).key!=getDateString().key){
			return getDateString(timestamp).timeString+' '+getTimeString(timestamp).timeString
		}else{
			return getTimeString(timestamp).timeString
		};
	},
	browers:{
		versions:function(){
	        var u = navigator.userAgent, app = navigator.appVersion;
	        return {
	            trident: u.indexOf('Trident') > -1, //IE内核
	            presto: u.indexOf('Presto') > -1, //opera内核
	            webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
	            gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1,//火狐内核
	            mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
	            ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
	            android: u.indexOf('Android') > -1 || u.indexOf('Adr') > -1, //android终端
	            iPhone: u.indexOf('iPhone') > -1 , //是否为iPhone或者QQHD浏览器
	            iPad: u.indexOf('iPad') > -1, //是否iPad
	            webApp: u.indexOf('Safari') == -1, //是否web应该程序，没有头部与底部
	            weChat: u.indexOf('MicroMessenger') > -1, //是否微信 （2015-01-22新增）
	            qq: u.match(/\sQQ/i) == " qq" //是否QQ
	        };
	    }(),
		isAndroid: function(){
			var me = this;
			return me.versions.android;
		},
		isweChat: function(){
			var me = this;
			return me.versions.weChat;
		},
		isIos: function(){
			var me = this;
			return me.versions.ios;
		},
		isMobile:function(){
			var me = this;
			return me.versions.mobile;
		}
	},
	OSSUpFile(sendFileObj,callback){
  		var imageForm = new FormData();
		imageForm.append('file',sendFileObj.dom.files[0]);
		this.AJAX.FromData('POST','httpChat/uploadFile',imageForm,data=>{
			if(typeof callback == 'function'){
				callback({
					fileKey:data.fileKey,
					fileType:data.fileType,
					fileName:data.fileName
				});
			};
		});
  	},
	File:{
		upFileInfo:{
			isCreate:false,
			inputDom:null,
			getFileParamsArray:[],
			getFileCallBack:null,
			accept:'',
			capture:'',
			multiple:'',
			isPreView:true,
			createBase64:false,
		},
		getParams:function(params,defaultOption) {
			/* TODO 私有方法 不能直接调用 */
			var tempParams=new Object();
			if(params!=undefined){
				for(var key in defaultOption){
					tempParams[key]=params[key]==undefined?defaultOption[key]:params[key];
					if(defaultOption[key]==null){
						defaultOption[key]=params[key]
					};
				};
			}else{
				tempParams=defaultOption;
			};	
			return tempParams;
		},
		chooseFile:function(optionfile){
			var getBase64=function(file,callback){
				console.log('正在处理图片…');
				var reader = new FileReader();
		        reader.readAsDataURL(file); 
		        reader.onload = function(e){
		        	var getBase64 = this.result;
		            if(typeof callback=='function'){
		            	console.log('getBase64完成');
		            	callback(getBase64);
		            };
		        };   
			};
			this._reset_upFileInfo();	//clear upFileInfo
			var _optionsFile=this.upFileInfo;
			var params=this.getParams(optionfile,this.upFileInfo);
			_optionsFile.inputDom= document.createElement("input");
			_optionsFile.inputDom.id='toc_upFile_input';
			_optionsFile.inputDom.type='file';
			if(!units.browers.isIos()){
				_optionsFile.inputDom.accept=params.accept;
				_optionsFile.inputDom.capture=params.capture;
				if(params.capture!=null||params.capture!=''){
					_optionsFile.inputDom.multiple='';
				}else{
					_optionsFile.inputDom.multiple=params.multiple?'multiple':'';
				};
			};
			document.body.appendChild(_optionsFile.inputDom);
			_optionsFile.inputDom.style.display='none';
			$("#toc_upFile_input").click();
			_optionsFile.inputDom.onchange=function(e){	
				_optionsFile.getFileParamsArray=[];
				for(var a=0;a<e.target.files.length;a++){
					var getFileInfo=e.target.files[a];
					if(params.createBase64){
						getBase64(getFileInfo,function(base64){
							_optionsFile.getFileParamsArray.push({
								name:getFileInfo.name,
			   					size:getFileInfo.size,
			   					type:getFileInfo.type,
			   					preViewSrc:params.isPreView?URL.createObjectURL(getFileInfo):null,
			   					base64:base64
							});
							if(typeof params.getFileCallBack=='function'){
								document.body.removeChild(_optionsFile.inputDom);
								params.getFileCallBack({
									dom:_optionsFile.inputDom,
									info:_optionsFile.getFileParamsArray
								});
							};		
						});
					}else{
						_optionsFile.getFileParamsArray.push({
							name:getFileInfo.name,
		   					size:getFileInfo.size,
		   					type:getFileInfo.type,
		   					preViewSrc:params.isPreView?URL.createObjectURL(getFileInfo):null,
		   					base64:null
						});
						if(typeof params.getFileCallBack=='function'){
							document.body.removeChild(_optionsFile.inputDom);
							params.getFileCallBack({
								dom:_optionsFile.inputDom,
								info:_optionsFile.getFileParamsArray
							});
						};	
					};
				};				
			};
		},
		_reset_upFileInfo:function(){
			/*if(this.upFileInfo.inputDom!=null){
				document.body.removeChild(this.upFileInfo.inputDom);
			};	*/		
			this.upFileInfo={
				isCreate:false,
				inputDom:null,
				getFileParamsArray:[],
				getFileCallBack:null,
				accept:'',
				capture:'',
				multiple:'',
				isPreView:true,
				createBase64:false
			};
		}
	},
	Debounce:function(option){
		this.value=null;
		this.callback=option.callback;
		this.debounceftn=null;
		this.setValue=function(str){
			//console.log('setValue:',str)
			this.value =str;
		};
		this.getValue=function(){
			//console.log('getValue:',this.value)
			if(typeof this.callback =='function'){
				this.callback(this.value)
			};
		};
		this.initdebounce=function(){
			if(this.debounceftn==null){
				this.debounceftn=units.copy.debounce(this.getValue, 250, { 'maxWait': 1000 });
				return true
			}else{
				return false
			}
		} 
	},
	copy:{
		 debounce:function(func, wait, options) {
		    let lastArgs,
		        lastThis,
		        maxWait,
		        result,
		        timerId,
		        lastCallTime
		
		    // 参数初始化
		    let lastInvokeTime = 0 
		    let leading = false
		    let maxing = false
		    let trailing = true
		
		   	if (typeof func != 'function') {
		        throw new TypeError('Expected a function')
		    }
		    wait = +wait || 0
		 	/*if (isObject(options)) {
		        // 对配置的一些初始化
		    }*/
		
		    function invokeFunc(time) {
		        const args = lastArgs
		        const thisArg = lastThis
		
		        lastArgs = lastThis = undefined
		        lastInvokeTime = time
		        result = func.apply(thisArg, args)
		        return result
		    }
		
		    function leadingEdge(time) {
		        // Reset any `maxWait` timer.
		        lastInvokeTime = time
		        // 为 trailing edge 触发函数调用设定定时器
		        timerId = setTimeout(timerExpired, wait)
		        // leading = true 执行函数
		        return leading ? invokeFunc(time) : result
		    }
		
		   function remainingWait(time) {
		        const timeSinceLastCall = time - lastCallTime // 距离上次debounced函数被调用的时间
		        const timeSinceLastInvoke = time - lastInvokeTime // 距离上次函数被执行的时间
		        const timeWaiting = wait - timeSinceLastCall // 用 wait 减去 timeSinceLastCall 计算出下一次trailing的位置
		
		        // 两种情况
		        // 有maxing:比较出下一次maxing和下一次trailing的最小值，作为下一次函数要执行的时间
		        // 无maxing：在下一次trailing时执行 timerExpired
		        return maxing
		            ? Math.min(timeWaiting, maxWait - timeSinceLastInvoke)
		            : timeWaiting
		    }
		
		    // 根据时间判断 func 能否被执行
		    function shouldInvoke(time) {
		        const timeSinceLastCall = time - lastCallTime
		        const timeSinceLastInvoke = time - lastInvokeTime
		
		        // 几种满足条件的情况
		        return (lastCallTime === undefined 
		            || (timeSinceLastCall >= wait) // 距离上次被调用已经超过 wait
		            || (timeSinceLastCall < 0) //系统时间倒退
		            || (maxing && timeSinceLastInvoke >= maxWait)) //超过最大等待时间
		    }
		
		    function timerExpired() {
		        const time = Date.now()
		        // 在 trailing edge 且时间符合条件时，调用 trailingEdge函数，否则重启定时器
		        if (shouldInvoke(time)) {
		            return trailingEdge(time)
		        }
		        // 重启定时器，保证下一次时延的末尾触发
		        timerId = setTimeout(timerExpired, remainingWait(time))
		    }
		
		    function trailingEdge(time) {
		        timerId = undefined
		
		        // 有lastArgs才执行，意味着只有 func 已经被 debounced 过一次以后才会在 trailing edge 执行
		        if (trailing && lastArgs) {
		            return invokeFunc(time)
		        }
		        // 每次 trailingEdge 都会清除 lastArgs 和 lastThis，目的是避免最后一次函数被执行了两次
		        // 举个例子：最后一次函数执行的时候，可能恰巧是前一次的 trailing edge，函数被调用，而这个函数又需要在自己时延的 trailing edge 触发，导致触发多次
		        lastArgs = lastThis = undefined
		        return result
		    }
		
		    function cancel() {}
		
		    function flush() {}
		
		    function pending() {}
		
		    function debounced(...args) {
		        const time = Date.now()
		        const isInvoking = shouldInvoke(time) //是否满足时间条件
		
		        lastArgs = args
		        lastThis = this
		        lastCallTime = time  //函数被调用的时间
		
		        if (isInvoking) {
		            if (timerId === undefined) { // 无timerId的情况有两种：1.首次调用 2.trailingEdge执行过函数
		                return leadingEdge(lastCallTime)
		            }
		            if (maxing) {
		                // Handle invocations in a tight loop.
		                timerId = setTimeout(timerExpired, wait)
		                return invokeFunc(lastCallTime)
		            }
		        }
		        // 负责一种case：trailing 为 true 的情况下，在前一个 wait 的 trailingEdge 已经执行了函数；
		        // 而这次函数被调用时 shouldInvoke 不满足条件，因此要设置定时器，在本次的 trailingEdge 保证函数被执行
		        if (timerId === undefined) {
		            timerId = setTimeout(timerExpired, wait)
		        }
		        return result
		    }
		    debounced.cancel = cancel
		    debounced.flush = flush
		    debounced.pending = pending
		    return debounced
		}
	}
};

export default units